<?php

/*
 * CRM 通用函数
 * @since 1.0 2014-12-29 by sutroon
 */

/**
 * APP_ROOT_PATH 应用程序目录绝对路径(必须放在分组项目的Common中)
 * @since 1.0 2014-12-31 by sutroon
 */
define('APP_ROOT_PATH', $_SERVER['DOCUMENT_ROOT'] . __ROOT__ . '/' . APP_NAME . (defined('GROUP_NAME') ? ('/' . C('APP_GROUP_PATH') . '/' . GROUP_NAME) : '') . '/');

/**
 * 判断用户是否登录
 * @param type $sessionId
 * @return mixed
 * @since 1.0 <2015-3-23> SoChishun Added.
 */
function appfn_is_login($sessionId){
    $login_data=session($sessionId);
    return $login_data;
}

/**
 * 检测系统是否已经安装
 * @return boolean
 * @since 1.0 2015-3-23 SoChishun Added.
 */
function appfn_is_install(){
    return F('APP_IS_INSTALLED');
}
/**
 * 返回项目的AppData目录<br />包含Conf、Template、TempSqls等
 * @param array $options 选项,包含siteID, userID, type, subdir选项
 * @return string 返回路径地址
 * @since 1.0 2015-1-19 by sutroon
 * @example
 * get_appdata_dir(array('siteID'=>$this->loginData['siteID'],'userID'=>$this->loginData['id'],'type'=>'TempSqls','subdir'=>'CustomerImp')).date('Ymdhis').'.sql'; // 获取sql临时文件目录
 * get_appdata_dir(array('type'=>'Template')).'customer_import_file.xlsx'; // 获取模板文件
 * get_appdate_dir(array('type'=>'Conf')).'AppConf.conf'; // 获取配置文件
 */
function get_appdata_dir($options) {
    if (!$options || !is_array($options)) {
        return APP_ROOT_PATH . 'AppData/';
    }
    $dirs[] = 'AppData';
    $arrData = array('conf' => 'Conf', 'tempsqls' => 'TempSqls', 'template' => 'Template');
    if (isset($options['type'])) {
        $options['type'] = strtolower($options['type']);
        if (array_key_exists($options['type'], $arrData)) {
            $dirs[] = $arrData[$options['type']];
        }
    }
    if (isset($options['subdir'])) {
        $dirs[] = $options['subdir'];
    }
    $name = '';
    if (isset($options['siteID'])) {
        $name.='S' . $options['siteID'];
    }
    if (isset($options['userID'])) {
        $name.='U' . $options['userID'];
    }
    if ($name) {
        $dirs[] = $name;
    }
    $path = APP_ROOT_PATH . implode('/', $dirs);
    if (!is_dir($path)) {
        mkdir($path, 0777, true);
    }
    return ($path[strlen($path)] == '/') ? $path : $path . '/';
}

/**
 * 检测权限是否存在
 * @param string $code 权限代码
 * @param int $uid 用户编号
 * @return bool
 * @since 1.0 2014-7-24 by sutroon
 * @example equal_permission('YH_YGGL', $this->loginData['id'])
 */
function equal_permission($code, $uid) {
    $cache_id = 'userPermissionRule' . $uid;
    $str = S($cache_id);
    if (!$str) {
        $str = M('tuser')->where("id=$uid")->getField('permissionRule');
        S($cache_id, $str, array('expire' => 30));
    }
    if (!$str) {
        return false;
    }
    $ruleID = M('tuser_permission')->where("code='$code'")->getField('id');
    if (!$ruleID) {
        return false;
    }
    if (false === strpos(",$str,", ",$ruleID,")) {
        return false;
    }
    return true;
}

/**
 * 获取订单状态描述
 * @param string $target, 流程主体,如:xcallcrm
 * @param int $val 状态值
 * @return string
 * @since 1.0 2015-1-9 by sutroon
 * @example get_order_state_text('xcallcrm',0);
 */
function get_order_state_text($type, $val) {
    $arr_states = array('0' => '未审核', '1' => '交易完成', '20' => '核单通过', '24' => '核单失败', '30' => '已发货', '未签收', '34' => '仓库退回', '40' => '座席取消', '41' => '买家取消', '42' => '逾期取消', '43' => '订单无效取消', '50' => '客户签收', '54' => '客户拒签', '55' => '客户退货');
    return array_key_exists($val, $arr_states) ? $arr_states[$val] : "未知[$val]";
}

/**
 * 生成序列号(支持10亿以下不重复序号)
 * 规则：[前缀][siteID1|9]0[userID1|9][timestamp14]
 * 生成位数：17-33
 * @param string $prefix 前缀,DD=订单,KH=客户,CZ=充值
 * @param int $siteID
 * @param int $uid
 * @return string
 * @since 1.0 2014-1-9 by sutroon
 */
function get_serialNo($prefix, $siteID, $uid) {
    return $prefix . $siteID . '0' . $uid . date('Ymdhis');
}

/**
 * 语音管理-获取语音路径
 * @param string $tag 类型
 * @return string
 * @since 1.0 2014-7-24 by sutroon
 */
function get_cti_media_url($tag) {
    switch ($tag) {
        case 'moh': // /var/lib/asterisk/moh
            return 'http://' . $_SERVER['SERVER_NAME'] . ':8897';
        case 'sounds': // /var/lib/asterisk/sounds
            return 'http://' . $_SERVER['SERVER_NAME'] . ':8896';
        case 'rec': // /var/spool/asterisk/monitor
            return 'http://' . $_SERVER['SERVER_NAME'] . ':8898/';
    }
    return '';
}

/**
 * 处理录音文件地址
 * @param string $file
 * @return string
 * @since 1.0 2014-7-24 by sutroon
 */
function get_cti_recfile_url($file) {
    // q-2000-18679753678-20140814-223101-1408026661.3643.WAV
    // /monitor/2014/08/10/
    if (strpos($file, '-') === false) {
        return $file;
    }
    $arr = explode('-', $file);
    $path = $arr[3];
    return substr($path, 0, 4) . '/' . substr($path, 4, 2) . '/' . substr($path, 6) . '/' . $file;
}



    /**
     * 获取租户列表
     * 格式：array(siteID=>userName[siteID])
     * @param array $prepend
     * @return array
     * @since 1.0 2014-10-21 by sutroon
     */
    function get_users($prepend = array('' => '选择租户')) {
        $list = S('admin_siteid_names');
        if (!$list) {
            $list = M('tuser')->where("userType='ADMIN'")->getFields(array('siteID', "concat(userName,'[',siteID,']') as userName"));
            S('admin_id_names', $list, array('expire' => 15));
        }
        if ($list && $prepend) {
            $list = $prepend + $list;
        }
        return $list;
    }

    /**
     * 获取座席列表
     * @param int $siteID
     * @param array $prepend
     * @return array
     * @since 1.0 2014-12-29 by sutroon
     */
    function get_seats($siteID = 0, $prepend = array('' => '选择工号')) {
        if (!$siteID) {
            $siteID = $this->loginData['siteID'];
        }
        $list = S('seat_id_names');
        if (!$list) {
            $list = M('tuser')->where("siteID=$siteID and userType='SEAT'")->getFields(array('userName as id', "userName"));
            S('seat_id_names', $list, array('expire' => 15));
        }
        if ($list && $prepend) {
            $list = $prepend + $list;
        }
        return $list;
    }

    /**
     * 设置数据集列表的siteID值
     * @param $list
     * @since 1.0 2014-10-25 by sutroon
     */
    function set_siteID_text($list, $col = null) {
        if (!$list || false === $col) {
            return $list;
        }
        $users =get_users(array());
        if (is_null($col)) {
            $col = 'siteID';
        }
        foreach ($list as $row) {
            $siteID = $row[$col];
            $row[$col] = isset($users[$siteID]) ? $users[$siteID] : $siteID;
            $arr[] = $row;
        }
        return $arr;
    }